<?php
/**
 * funadmin
 * ============================================================================
 * 版权所有 2018-2027 funadmin，并保留所有权利。
 * 网站地址: https://www.funadmin.com
 * ----------------------------------------------------------------------------
 * 采用最新Thinkphp6实现
 * ============================================================================
 * Author: yuege
 * Date: 2019/9/4
 */
namespace addons\wechat\backend\controller;
use addons\wechat\backend\model\WechatAccount;
use think\App;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use fun\helper\DataHelper;
use addons\wechat\backend\model\WechatMaterialInfo;
use addons\wechat\backend\model\WechatMaterial;

class Index extends WxBase {

    public function __construct(App $app)
    {
        parent::__construct($app); // TODO: Change the autogenerated
        $this->modelClass = new WechatAccount();
    }


    //获取素材
    public function getMaterialByType(){
        $type = $this->request->post('type');
//      $type text 素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）

//      $res = $this->wxapp->material->list($type,0,100);
        $res =  WechatMaterial::where($this->where)->where('type',$type)
            ->where($this->where)->select()->toArray();
        if($type ==='news'){
            foreach ($res as $k=>$v){
                $res[$k]['groupList'] = WechatMaterialInfo::where($this->where)->where('material_id',$v['id'])->select()->toArray();
            }
        }
        $this->success(lang('get data success'),'',$res);


    }


    /**
     ********************************上传素材接口***************************************
     */

    protected function uploads($type,$uploadPath='uploads'){

        //获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        for ($i = 0; $i < count($fileKey); $i++) {
            //获取表单上传文件
            $file = request()->file($fileKey[$i]);
            try {
                validate($type)->check(DataHelper::objToArray($file));
//                validate(syscfg('upload','upload_type'))->check($file);
                $savename = \think\facade\Filesystem::disk('public')->putFile($uploadPath, $file);
                $path[] = '/storage/' . $savename;
            } catch (\think\exception\ValidateException $e) {
                $path = '';
                $error = $e->getMessage();
            }
        }
        if (!empty($path)) {
            $result['code'] = 1;
            //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
            if (Request::param('responseType') == 'json') {
                $result["url"] = $path[0];
            } else {
                $result["url"] = $path[0];
            }
            $result['msg'] = lang('upload success');
            return $result;
        } else {
            //上传失败获取错误信息
            $result['url'] = '';
            $result['msg'] = $error;
            $result['code'] = 0;
            return $result;
        }


    }
    public function imageUpload(){

        $res = $this->uploads($this->imageValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wxapp->material->uploadImage('./'.$res['url']);
            $this->showError($result);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            $r = WechatMaterial::create($data);
            if($r){
                $this->success(lang('upload success'),'',$result);
            }else{
                $this->error('上传失败');

            }
        }else{
            $this->error('上传失败');

        }
    }

    public function videoUpload(){
        $data = $this->request->post();
        if(!$data['url'] || !$data['file_name'] || !$data['des']){
            $this->error('数据不能为空');
        }
        $result = $this->wxapp->material->uploadVideo('.'.$data['url'],$data['file_name'],$data['des']);
        $this->showError($result);
        $resource = $this->wxapp->material->get($result['media_id']);
        $datas  = [
            'media_id'=> $result['media_id'],
            'media_url'=> $resource['down_url'],
            'local_cover'=> $data['url'],
            'type'=> 'video',
            'file_name'=> $data['file_name'],
            'des'=> $data['des'],
        ];
        $result['url'] = $resource['down_url'];

        $r = WechatMaterial::create($datas);
        if($r){
            $this->success(lang('upload success'),'',$result);
        }else{
            $this->error('上传失败');

        }


    }

    public function voiceUpload(){
        $res = $this->uploads($this->voiceValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wxapp->material->uploadVoice('./'.$res['url']);
            $this->showError($result);
            $resource = $this->wxapp->material->get($result['media_id']);

            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],

                'type'=> 'image',
            ];
            $result['url'] = $resource['down_url'];
            $r = WechatMaterial::create($data);
            if($r){
                $this->success(lang('upload success'),'',$result);
            }else{
                $this->error('上传失败');

            }
        }else{
            $this->error('上传失败');

        }

    }


    public function thumbUpload(){
        $res = $this->uploads($this->thumbValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wxapp->material->uploadThumb('./'.$res['url']);
            $this->showError($result);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            $r = WechatMaterial::create($data);
            if($r){
                $this->success(lang('upload success'),$result['url']);
            }else{
                $this->error(lang('upload fail'));

            }
        }else{
            $this->error(lang('upload fail'));

        }


    }

    public function UeditUploadImage(){

        $res = $this->uploads($this->imageValidate);
        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wxapp->material->uploadImage('./'.$res['url']);
            $this->showError($result);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $result['url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];

            $r = WechatMaterial::create($data);
            $data = ['state'=>'SUCCESS','url'=>$data['media_url']];

        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json($data);

    }

    public function UeditUploadVideo(){
        $res = $this->uploads($this->videoValidate);

        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wxapp->material->uploadVideo('./'.$res['url'],$res['url'],$res['url']);
            $this->showError($result);
            $resource = $this->wxapp->material->get($result['media_id']);

            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],
                'type'=> 'video',
                'file_name'=> $res['url'],
                'des'=> $res['url'],
            ];
            $result['url'] = $resource['down_url'];
            $r = WechatMaterial::create($data);

            $data = ['state'=>'SUCCESS','url'=>$resource['down_url']];
        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json_encode($data);

    }

    public function UeditUploaVoice(){

        $res = $this->uploads($this->voiceValidate);

        if($res['code']>0){
            //路劲用相对路径
            $result = $this->wxapp->material->uploadVoice('./'.$res['url']);
            $this->showError($result);
            $resource = $this->wxapp->material->get($result['media_id']);
            $data  = [
                'media_id'=> $result['media_id'],
                'media_url'=> $resource['down_url'],
                'local_cover'=> $res['url'],
                'type'=> 'image',
            ];
            $result['url'] = $resource['down_url'];
            $r = WechatMaterial::create($data);

            $data = ['state'=>'SUCCESS','url'=>$resource['down_url']];
        }else{
            $data = ['state'=>'SUCCESS','url'=>''];

        }
        return json_encode($data);
    }
    public function getListImage(){
        $list = WechatMaterial::where($this->where)->where('type','image')->select();
        $data = ['state'=>'SUCCESS','start'=>0,'total'=>count($list),'list'=>[]];
        if($list){
            foreach ($list as $k=>$v) {
                $data['list'][$k]['url'] = $v['media_url'];
                $data['list'][$k]['mtime'] = time();
            }
        }

        return json_encode($data);

    }
    // 微信返回数据
    protected  function showError($res){
        if(isset($res['errcode']) && $res['errcode']>0){
            $this->error($res['errmsg']);
        }

    }

    //获取媒体素材
    protected function getMaterialByMediaId($mediaId){
        $resource = $this->wxapp->material->get($mediaId);
        $this->showError($resource);
        return $resource;

    }
}